(function(w){
	
	var _b = function (form){
        var evs =$._data($("#"+form)[0], "events");
        var b = (undefined == evs ? undefined : evs.beforequery ) ;
        delete evs;
        if(!_q.isEmpty(b)){
            var r = b[0].handler.apply($("#"+form)[0],arguments);
            if(false == r) return false;
        }
        return true;
    };

    var _a = function (form){
        var evs =$._data($("#"+form)[0], "events");
        var b = (undefined == evs ? undefined : evs.afterquery ) ;
        delete evs;
        if(!_q.isEmpty(b)){
            var r = b[0].handler.apply($("#"+form)[0],arguments);
            if(false == r) return false;
        }
        return true;
    };
	
	var reloadGrid = function (q,grid){
        var p = $("#"+grid).jqGrid("getGridParam", "postData"); 
        //定义个字符串 和一个数组
        //queryJson: json2Str(q)
        var where_ = null;
        var args_ = [];
        if(q.length > 0){
            for(var i = 0 ; i < q.length  ; i++){
                if(i == 0){
                    where_ = "  " + q[i].field + " " + q[i].op + " ?" ;
                    if(q[i].op ==  'like'){
                        args_.push("%"+q[i].data+"%");
                    }else{
                        args_.push(q[i].data);
                    }
                   
                }else{
                    where_ = where_ + " and " + q[i].field + " " + q[i].op + " ?" ;
                    if(q[i].op ==  'like'){
                        args_.push("%"+q[i].data+"%");
                    }else if(q[i].type  == 'date'){
                    	//后期时间查询扩展功能
	                      if(q[i].op  ==  '>='){
		                   	 args_.push(q[i].data);
		                   }else if(q[i].op ==  '<='){
		                  	 args_.push(q[i].data+" 23:59:59");
		                   }

                    }else{
                        args_.push(q[i].data);
                    }
                }
            } 
            console.log(where_);
            console.log(args_);
            $.extend(p, {where_: where_,args_:args_}); 
        }else{
            $.extend(p, {where_: null,args_:null});
        }

        $("#"+grid).jqGrid("setGridParam", {  
            search: true    
        }).trigger("reloadGrid", [{page:1}]);

        delete p;
    };
	
	
	
	//对外提供的api方法
	var _q = {
		//查询相关
		queryGrid: function(form,grid){
			if(!_b(form)) return false; 
			var q = [];
			$("#"+form+" input[ifield]").each(function(){
				if(!_q.isEmpty($(this).val()))
					q.push({name:$(this).attr('id'), field:$(this).attr('ifield'),op:$(this).attr('ioperation')
						,type:$(this).attr('idatatype'),data:$(this).val()
						,ignorecase:$(this).attr('ignorecase')});
			});
			$("#"+form+" select[ifield]").each(function(){
				if(!_q.isEmpty($(this).val()) && $(this).val() != "null"&&$(this).val() !="? undefined:undefined ?")
					q.push({field:$(this).attr('ifield'),op:$(this).attr('ioperation')
						,type:$(this).attr('idatatype'),data : $(this).val()});
			});
			//增加排序字段
			// $("#"+form+" input[name='q_sort_input_hid']").each(function(){
			//     if(!_q.isEmpty($(this).val())) {
			//         var arr = $(this).val().split(",");
			//         for(var i=0; i<arr.length; i++) {
			//             var vals = arr[i].split(":");
			//             q.push({field: vals[0], order: vals[1]});
			//         }
			//     }
			// });
			
				//if(q.length >0) {
					reloadGrid(q,grid);
					_a(form);
				//}
		 },

		 reset: function (form){
			$("#"+form+" input[type=\"text\"]").val('');
			$("#"+form+" input[type=\"hidden\"]").val('');
			$("#"+form+"  select").val('');
			$("#"+form+"  textarea").val('');
			$("#"+form+"  :checkbox").removeAttr("checked");
			$("#"+form+"  :radio").removeAttr("checked");
		 },
		
		
		

		isEmpty: function (p){
			if(p == null || p == "" || p == undefined)
			return true;
		},

		/**
		暴露给jqgrid调用，返回分页数据
		*/
		retrieveData: function (grid, postdata, tablename,callBack) {
			var _sql = "select * from " + tablename;
			if(postdata.where_) {
				_sql += " where " + postdata.where_;
			}
			if(postdata.sidx) {
				_sql += " order by " + postdata.sidx;
				if(postdata.sord) {
					_sql += " " + postdata.sord;
				} else {
					_sql += " asc";
				}
			}
			db.pageBysql({ 
				sql : _sql,
				data: postdata.where_ ? postdata.args_ : [],
				page :{
					index :postdata.page,
					size : postdata.rows
				},
				success: function(res){
					if(callBack){
						callBack(res);	
					}else{
						grid.addJSONData(res);
					}
				},
				fail : function(err){
					console.error(err);
				}

			});
			 
		},
		/**
		暴露给jqgrid调用，返回分页数据
		*/
		retrieveFieldGroupData: function (grid, postdata, tablename,sqlfield,group,callBack) {
			var _sql = "select "+sqlfield+" from " + tablename;
			if(postdata.where_) {
				_sql += " where " + postdata.where_;
			}

			_sql += " "+group;
			if(postdata.sidx) {
				_sql += " order by " + postdata.sidx;
				if(postdata.sord) {
					_sql += " " + postdata.sord;
				} else {
					_sql += " asc";
				}
			}
			console.log(_sql);
			db.pageBysql({ 
				sql : _sql,
				data: postdata.where_ ? postdata.args_ : [],
				page :{
					index :postdata.page,
					size : postdata.rows
				},
				success: function(res){
					if(callBack){
						callBack(res);	
					}else{
						grid.addJSONData(res);
					}
				},
				fail : function(err){
					console.error(err);
				}

			});
			 
		},
		/**
		暴露给jqgrid调用，返回分页数据
		*/
		retrieveMutiData: function (grid, postdata, mutiSql,relation,group,callBack) {
			var _sql = mutiSql;
			if(relation){
				_sql += " where " + relation;
				if(postdata.where_) {
					_sql += " and " + postdata.where_;
				}
			}else{
				if(postdata.where_) {
					_sql += " where " + postdata.where_;
				}
			}
			_sql += " "+group;
			if(postdata.sidx) {
				_sql += " order by " + postdata.sidx;
				if(postdata.sord) {
					_sql += " " + postdata.sord;
				} else {
					_sql += " asc";
				}
			}
			console.log(_sql);
			db.pageBysql({ 
				sql : _sql,
				data: postdata.where_ ? postdata.args_ : [],
				page :{
					index :postdata.page,
					size : postdata.rows
				},
				success: function(res){
					if(callBack){
						callBack(res);	
					}else{
						grid.addJSONData(res);
					}
				},
				fail : function(err){
					console.error(err);
				}

			});
			 
		}
	};
	
	w.nzquery = _q;
	
})(window);
     